package com.dbsop.rest;

import com.dbsop.config.EsClientConfig;
import com.dbsop.config.EsHttpConfiguration;
import com.dbsop.mapper.ESBaseMapper;
import com.dbsop.operation.field.RestFieldOperation;
import com.dbsop.operation.index.RestIndexOperation;
import com.dbsop.request.ClientOpt;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import java.util.List;

@Slf4j
public class RestOpt extends ClientOpt {



    protected RestHighLevelClient restClient;

    public RestOpt(EsClientConfig esClientConfig, List<ESBaseMapper> esBaseMappers) {
        super(esClientConfig, esBaseMappers);

    }

    @Override
    protected void initOperation() {
        this.clientRequest = new RestRequest(restClient);
        this.fieldOperation = new RestFieldOperation(restClient);
        this.indexOperation = new RestIndexOperation(restClient);
    }

    public void initClient(){
        EsHttpConfiguration httpConfig = esClientConfig.getHttp();

        List<String> hosts = httpConfig.getHosts();
        RestClientBuilder builder = null;
        for (String host : hosts) {
            String[] split = host.split(":");
            builder = RestClient.builder(new HttpHost(split[0],Integer.valueOf(split[1]),"http"));
        }
        builder.setFailureListener(new RestClient.FailureListener(){
            @Override
            public void onFailure(Node node) {
                log.error("节点异常:"+ node.getName()+" <==>"+node.getHost());
            }
        });
        restClient =  new RestHighLevelClient(builder);
    }
}
